import {useState,useEffect} from 'react';
import {Table,Pagination, message } from 'antd';
import axios from 'axios';

const UserManage = (props) => {

  const [dataSource, setDataSource] = useState([]);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total,setTotal] = useState(0);

  const colums = [
    {
      key: "order",
      title:"序号",
      render:(text,record,index)=>{return (pageNo-1)*pageSize+index+1}
    },{
      key: "username",
      title:"用户名",
      dataIndex: "username",
      key:"username",
    },{
      key: "password",
      title:"密码",
      dataIndex: "password",
      key: "password",
    },{
      key: "action",
      title:"操作",
      render:(text,record,index)=>{
        return <a onClick={deleteUser.bind(this,record.id)}>删除</a>
      }
    }
  ];

  const deleteUser = (id) => {
    axios.post("http://localhost:8080/tuser/delete",
      `id=${id}`
    ).then(()=>{
      message.success("删除成功");
      getData().then((res)=>{
        setDataSource(res.data.rows);
        setTotal(res.data.total);
      })
    }).catch(()=>{
      message.error('删除失败')
    })
  }

  useEffect(()=>{
    getData().then((res)=>{
      setDataSource(res.data.rows);
      setTotal(res.data.total);
    })
  },[])

  const getData = (param) => {
    return(
      axios.post('http://localhost:8080/tuser/query',{
        param,
        pageNo: pageNo,
        pageSize: pageSize,
      })
    )
  }

  const onChange = (pageNo,pageSize) => {
    setPageNo(pageNo);
    setPageSize(pageSize);
  }

  return (<>
    <Table columns={colums} dataSource={dataSource} />
    <Pagination showQuickJumper defaultCurrent={1} total={total} pageSizeOptions={[10,20,50]} onChange={onChange} />
  </>)

}

export default UserManage;